<?php

App::uses('AppController', 'Controller');

/**
 * OrdenesTags Controller
 *
 * @property OrdenesTag $OrdenesTag
 */
class OrdenesController extends AppController {

    public $uses = array(
        'Ordene',
        'OrdenesTag',
        'Tag',
        'Categoria',
        'Documento',
        'DocumentosOrdene',
        'Cambiordene',
        'CambiordenesTag',
        'Plano',
        'PlanosTag');
    public $layout = 'epcm';
    public $helpers = array('Javascript', 'Ajax');

    public function insertar() {

        $tags = $this->Tag->find('all', array('recursive' => -1));
        $dcc = $this->Categoria->find('list', array('fields' => 'nombre'));
        $documentos = $this->Documento->find('all', array('recursive' => -1, 'order' =>
            'orden'));
        //$arraycrt = 'hola';
        //debug($tags);

        if (!empty($this->data)) {
            //debug($this->data);
            //exit;

            if ($this->Ordene->save($this->data)) {
                $ulId = $this->Ordene->getLastInsertID();
                //guardamos los documentos
                $arrayOrdenes = $this->data['DocumentosOrdene']['seleccionados'];
                //debug($arrayOrdenes);exit;
                $arrayVal = $this->data;
                if ($arrayOrdenes) {

                    //debug($arrayOrdenes);
                    //$cadena = preg_replace('/,/', '', $arrayOrdenes);
                    //$sel = str_split($cadena);
                    $modOrdenes = preg_replace('/,S/', '', $arrayOrdenes);
                    //debug($modOrdenes);exit;
                    //debug($modOrdenes);exit;
                    //debug($sel);
                    $sel = preg_split("/,/", $modOrdenes);
                    //$arrayVal = $this->data;
                    if ($sel[0] != 'S') {
                        //$arrayVal = $this->data;
                        //debug($this->request->data);
                        for ($i = 0; $i < count($sel); $i++) {
                            $val = $sel[$i];
                            $this->data = "";
                            $this->DocumentosOrdene->create();

                            if (empty($arrayVal['DocumentosOrdene'][$val]['volumen'])) {
                                $this->request->data['DocumentosOrdene']['volumen'] = 0;
                            } else {
                                $this->request->data['DocumentosOrdene']['volumen'] = $arrayVal['DocumentosOrdene'][$val]['volumen'];
                            }

                            //$this->request->data['DocumentosOrdene']['volumen'] = $arrayVal['DocumentosOrdene'][$val]['volumen'];

                            $this->request->data['DocumentosOrdene']['documento_id'] = $arrayVal['DocumentosOrdene'][$val]['documento_id'];
                            if (empty($arrayVal['DocumentosOrdene'][$val]['original'])) {
                                $this->request->data['DocumentosOrdene']['original'] = 0;
                            } else {
                                $this->request->data['DocumentosOrdene']['original'] = $arrayVal['DocumentosOrdene'][$val]['original'];
                            }

                            $this->request->data['DocumentosOrdene']['ordene_id'] = $ulId;
                            $this->DocumentosOrdene->save($this->data);
                            //debug($this->data);
                            //debug($sel[$i]);
                        }
                    } else {
                        
                    }
                } else {
                    echo 'Se encontro';
                }
                //fin guarda documentos
                //echo 'guardo';

                foreach ($arrayVal['OrdenesTag'] as $d) {
                    $this->data = "";
                    $this->OrdenesTag->create();
                    $this->request->data['OrdenesTag']['ordene_id'] = $ulId;
                    $this->request->data['OrdenesTag']['tag_id'] = $d['tag'];

                    if (empty($d['nactivo'])) {
                        $this->request->data['OrdenesTag']['nactivo'] = $d['tag'];
                    } else {
                        $this->request->data['OrdenesTag']['nactivo'] = $d['nactivo'];
                    }

                    $this->request->data['OrdenesTag']['monto'] = $d['monto'];
                    //debug($this->request->data); exit;
                    $this->OrdenesTag->save($this->data);
                }
                $this->Session->setFlash("Orden Registrada!!!");

                $this->redirect(array('action' => 'corden', $ulId));
            }
        }
        $this->set(compact('tags', 'dcc', 'documentos'));
    }

    public function ajaxcambiosa($id = null) {
        $this->set($id);
    }

    public function editartagsorden($id = null) {

        $this->OrdenesTag->id = $id;
        //$dcc = $this->Categoria->find('list', array('fields' => 'nombre'));
        if ($this->request->is('get')) {
            $this->request->data = $this->OrdenesTag->read();
        } else {
            if ($this->OrdenesTag->save($this->request->data)) {
                $this->Session->setFlash('Your post has been updated.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to update your post.');
            }
        }
        //$this->set(compact('dcc'));
    }

    public function calc() {
        
    }

    public function detalle($id = null) {

        $orden = $this->Ordene->find('first', array('conditions' => array('Ordene.id' =>
                $id)));

        /* $documentos = $this->DocumentosOrdene->find('all', array(
          'recursive' => 2,
          'conditions' => array('DocumentosOrdene.ordene_id' => $id)
          )); */
        //debug($orden);
        $sqlDoc = "SELECT doc.volumen, doc.original, doc.documento_id, documentos.nombre
                    FROM documentos_ordenes doc
                    LEFT JOIN documentos ON doc.documento_id = documentos.id
                    WHERE doc.ordene_id = $id";
        $documentos = $this->DocumentosOrdene->query($sqlDoc);
        //debug($documentos);
        $tagsOrdenes = $this->OrdenesTag->find('all', array('recursive' => 3,
            'conditions' => array('OrdenesTag.ordene_id' => $id)));
        //debug($tagsOrdenes);

        $sqlOrdenesTags = "SELECT ot.ordene_id, ot.tag_id, ot.monto, tags.descripcion1
                            FROM ordenes_tags ot
                            LEFT JOIN tags ON ot.tag_id = tags.id
                            WHERE ot.ordene_id = $id";

        $ordenesTags = $this->OrdenesTag->query($sqlOrdenesTags);

        //$sqlOrdenesCo = "SELECT *      FROM ";
        $cambiosO = $this->Cambiordene->find('all', array(
            'recursive' => -1,
            'conditions' => array('ordene_id' => $id),
            'order' => array('numero ASC')));

        //debug($cambiosO);
        //debug($ordenesTags);
        $this->set(compact('orden', 'tagsOrdenes', 'documentos', 'ordenesTags', 'cambiosO'));
    }

    public function editadoc($idOrden = null) {
        $sqlDoc = "SELECT doc.id, doc.volumen, doc.original, doc.documento_id, documentos.nombre
                    FROM documentos_ordenes doc
                    LEFT JOIN documentos ON doc.documento_id = documentos.id
                    WHERE doc.ordene_id =$idOrden";
        $documentos = $this->DocumentosOrdene->query($sqlDoc);
        $this->set(compact('documentos', 'idOrden'));
    }

    public function index() {

        $ordenes = $this->Ordene->find('all', array('recursive' => 0));
        $this->set(compact('ordenes'));
    }

    public function cambiosorden($id = null) {
        $orden = $this->Ordene->find('first', array('recursive' => -1, 'conditions' =>
            array('id' => $id)));
        if (!empty($this->data)) {
            //debug($this->data);
            //if($this->Cambiordene->saveMany($this->data)){
            //$this->redirect(array('action'=>'index'));
            //}
        }
        $this->set(compact('id', 'orden'));
    }

    public function corden($id = null) {

        $cambiosO = $this->Cambiordene->find('all', array(
            'recursive' => -1,
            'conditions' => array('ordene_id' => $id),
            'order' => array('numero ASC')));
        $orden = $this->Ordene->find('first', array('recursive' => 2, 'conditions' =>
            array('Ordene.id' => $id)));
        $norden = $this->Cambiordene->find('first', array(
            'recursive' => -1,
            'conditions' => array('ordene_id' => $id),
            'order' => 'id DESC'));

        if (!empty($this->data)) {
            //debug($this->data);exit;
            $datos = $this->data;
            if ($this->Cambiordene->save($this->data)) {
                $ulCam = $this->Cambiordene->getLastInsertID();
                foreach ($this->data['CambiordenesTag'] as $cot) {
                    $this->data = "";
                    $this->CambiordenesTag->create();
                    $this->request->data['CambiordenesTag']['cambiordene_id'] = $ulCam;
                    $this->request->data['CambiordenesTag']['tag_id'] = $cot['tag'];
                    $this->request->data['CambiordenesTag']['monto'] = $cot['monto'];
                    //$this->request->data['CambiordenesTag']['nactivo'] = $cot['nactivo'];
                    if (empty($cot['nactivo'])) {
                        $this->request->data['CambiordenesTag']['nactivo'] = $cot['tag'];
                    } else {
                        $this->request->data['CambiordenesTag']['nactivo'] = $cot['nactivo'];
                    }
                    $this->CambiordenesTag->save($this->data);
                }
                $this->Session->setFlash("Cambio de Orden registado");
                $this->redirect(array('action' => 'corden', $id));
                //echo 'guardo';
            }

            //debug($this->data);
        }
        $this->set(compact('id', 'orden', 'cambiosO'));
    }

    public function editartags($idOrden = null) {
        //debug($idOrden);
        $sqlOrdenesTags = "SELECT ot.id, ot.ordene_id, ot.tag_id, ot.monto, tags.descripcion1
                            FROM ordenes_tags ot
                            LEFT JOIN tags ON ot.tag_id = tags.id
                            WHERE ot.ordene_id = $idOrden";
        $datosOrden = $this->Ordene->find('first', array('recursive' => -1, 'conditions' =>
            array('id' => $idOrden)));

        $ordenesTags = $this->OrdenesTag->query($sqlOrdenesTags);
        $this->set(compact('ordenesTags', 'idOrden', 'datosOrden'));
    }

    public function insertartags() {

        if (!empty($this->data)) {
            if ($this->OrdenesTags->save($this->data)) {
                $this->Session->setFlash('Se Guardo Correctamente!!!');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Error al Guardar consulte con el Administrador de Sistema');
            }
        }
    }

    public function eliminartags($id = null) {
        $this->OrdenesTags->id = $id;
        $this->data = $this->OrdenesTags->read();
        if (!$id) {
            $this->Session->setFlash('No existe la Orden Tags a Eliminar');
            $this->redirect(array('action' => 'index'));
        } else {
            if ($this->OrdenesTags->delete($id)) {
                $this->Session->setFlash('Se elimino la Orden Tags' . $this->data['OrdenesTags']['nombre']);
                $this->redirect(array('controller' => 'Ordenes', 'action' => 'index'));
            } else {
                $this->Session->setFlash('Error al eliminar');
            }
        }
    }

    public function editaco($idOrden = null) {

        $cambiosO = $this->Cambiordene->find('all', array(
            'recursive' => -1,
            'conditions' => array('ordene_id' => $idOrden),
            'orden' => array('numero ASC')));
        $this->set(compact('cambiosO', 'idOrden'));
    }

    public function editar($id = null) {
	
        $this->Ordene->id = $id;
		
        $dcc = $this->Categoria->find('list', array('fields' => 'nombre'));
        if ($this->request->is('get')) {
            $this->request->data = $this->Ordene->read();
        } else {
            if (empty($this->data['Ordene']['tsa'])) {
                $this->request->data['Ordene']['tsa'] = 0;
            }

            if ($this->Ordene->save($this->request->data)) {
                $this->Session->setFlash('Your post has been updated.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to update your post.');
            }
        }
        $this->set(compact('dcc'));
    }

    public function eliminar($id = null) {
        $this->Ordene->id = $id;
        $this->data = $this->Ordene->read();
        if (!$id) {
            $this->Session->setFlash('No existe la Orden a eliminar');
            $this->redirect(array('action' => 'index'));
        } else {
            if ($this->Ordene->delete($id)) {
                $this->Session->setFlash('Se elimino la Orden ' . $this->data['Ordene']['nombre']);
                $this->redirect(array('controller' => 'Ordenes', 'action' => 'index'));
            } else {
                $this->Session->setFlash('Error al eliminar');
            }
        }
    }

    public function aderirdoc($idOrden = null) {
        //$idOrden = $this->DocumentosOrdene->find('first', array(''));
        $datosOrden = $this->Ordene->find('first', array('recursive' => -1, 'conditions' =>
            array('id' => $idOrden)));

        $dcd = $this->Documento->find('list', array('fields' => array('nombre')));
        if (!empty($this->data)) {
            //debug($this->data);exit;
            if ($this->DocumentosOrdene->saveMany($this->data)) {
                //$this->Session->setFlash('Se guardo');
                $this->redirect(array(
                    'controller' => 'Ordenes',
                    'action' => 'editadoc',
                    $idOrden));
            }
        } else {
            
        }
        $this->set(compact('dcd', 'idOrden', 'datosOrden'));
    }

    public function insertartsa() {

        $tags = $this->Tag->find('all', array('recursive' => -1));
        $dcc = $this->Categoria->find('list', array('fields' => 'nombre'));
        $documentos = $this->Documento->find('all', array('recursive' => -1, 'order' =>
            'orden'));
        //$arraycrt = 'hola';
        //debug($tags);

        if (!empty($this->data)) {
            //debug($this->data);
            //exit;

            if ($this->Ordene->save($this->data)) {
                $ulId = $this->Ordene->getLastInsertID();
                //guardamos los documentos
                $arrayOrdenes = $this->data['DocumentosOrdene']['seleccionados'];
                //debug($arrayOrdenes);exit;
                $arrayVal = $this->data;
                if ($arrayOrdenes) {

                    //debug($arrayOrdenes);
                    //$cadena = preg_replace('/,/', '', $arrayOrdenes);
                    //$sel = str_split($cadena);
                    $modOrdenes = preg_replace('/,S/', '', $arrayOrdenes);
                    //debug($modOrdenes);exit;
                    //debug($modOrdenes);exit;
                    //debug($sel);exit;
                    $sel = preg_split("/,/", $modOrdenes);
                    //$arrayVal = $this->data;
                    if ($sel[0] != 'S') {
                        //$arrayVal = $this->data;
                        //debug($this->request->data);
                        for ($i = 0; $i < count($sel); $i++) {
                            $val = $sel[$i];
                            $this->data = "";
                            $this->DocumentosOrdene->create();

                            if (empty($arrayVal['DocumentosOrdene'][$val]['volumen'])) {
                                $this->request->data['DocumentosOrdene']['volumen'] = 0;
                            } else {
                                $this->request->data['DocumentosOrdene']['volumen'] = $arrayVal['DocumentosOrdene'][$val]['volumen'];
                            }

                            //$this->request->data['DocumentosOrdene']['volumen'] = $arrayVal['DocumentosOrdene'][$val]['volumen'];

                            $this->request->data['DocumentosOrdene']['documento_id'] = $arrayVal['DocumentosOrdene'][$val]['documento_id'];
                            if (empty($arrayVal['DocumentosOrdene'][$val]['original'])) {
                                $this->request->data['DocumentosOrdene']['original'] = 0;
                            } else {
                                $this->request->data['DocumentosOrdene']['original'] = $arrayVal['DocumentosOrdene'][$val]['original'];
                            }

                            $this->request->data['DocumentosOrdene']['ordene_id'] = $ulId;
                            $this->DocumentosOrdene->save($this->data);
                            //debug($this->data);
                            //debug($sel[$i]);
                        }
                    } else {
                        
                    }
                } else {
                    echo 'Se encontro';
                }
                //fin guarda documentos
                //echo 'guardo';

                foreach ($arrayVal['OrdenesTag'] as $d) {
                    $this->data = "";
                    $this->OrdenesTag->create();
                    $this->request->data['OrdenesTag']['ordene_id'] = $ulId;
                    $this->request->data['OrdenesTag']['tag_id'] = $d['tag'];

                    if (empty($d['nactivo'])) {
                        $this->request->data['OrdenesTag']['nactivo'] = $d['tag'];
                    } else {
                        $this->request->data['OrdenesTag']['nactivo'] = $d['nactivo'];
                    }

                    $this->request->data['OrdenesTag']['monto'] = $d['monto'];
                    //debug($this->request->data); exit;
                    $this->OrdenesTag->save($this->data);
                }
                $this->Session->setFlash("Orden Registrada!!!");

                $this->redirect(array('action' => 'corden', $ulId));
            }
        }
        $this->set(compact('tags', 'dcc', 'documentos'));
    }

    public function insertarplanos($idOrden = null) {
        
        $planos = $this->Plano->find('all', array(
            'recursive' => -1,
            'conditions' => array('ordene_id' => $idOrden)
                ));

        $dcc = $this->Categoria->find('list', array('fields' => 'nombre'));

        $orden = $this->Ordene->find('first', array(
            'recursive' => -1,
            'conditions' => array('id' => $idOrden)
                ));
        //debug($this->data);
        //exit;
        if (!empty($this->data)) {
                        
            //unset($this->Plano->PlanosTag->validate['plano_id']);
            //$this->Company->saveAssociated($this->request->data);
            if ($this->Plano->save($this->request->data)) {
                
                $ulPlano = $this->Plano->getLastInsertID();                        
                //$this->request->data['PlanosTag']['plano_id']=$ulPlano;                                
                foreach($this->request->data['PlanosTag'] as $pt)
                {
                    $this->request->data="";
                    $this->PlanosTag->create();
                    $this->request->data['PlanosTag']['plano_id']=$ulPlano;
                    $this->request->data['PlanosTag']['tag_id']=$pt['tag_id'];
                    $this->PlanosTag->save($this->request->data);
                }    
                $this->Session->setFlash('Se Guardo Correctamente!!!');
                $this->redirect(array('controller'=>'Planos', 'action' => 'index'));
            } else {
                $this->Session->setFlash('Error al Guardar consulte con el Administrador de Sistema');
            }
        }

        $this->set(compact('idOrden', 'planos', 'orden', 'dcc'));
    }

}